package com.qlogic.commons.utils.jee;

import java.util.Hashtable;

import javax.naming.Context;
import javax.naming.NamingException;

import com.qlogic.commons.utils.strings.StringUtils;

/**
 * <a href="JNDIUtils.java.html"><b><i>View Source</i></b></a>
 * 
 * @author H.LAMALMI
 * 
 */
public class JNDIUtils {

	public static Object lookup(Context ctx, String location)
			throws NamingException {
		return lookup(ctx, location, false);
	}

	public static Object lookup(Context ctx, String location, boolean exactName)
			throws NamingException {
		return lookup(ctx, location, exactName, false);
	}

	public static Object lookup(Context ctx, String location, boolean exactName, boolean cache)
			throws NamingException {
		Object obj = null;
		if (cache) {
			obj = cachedObjects.get(location);
			if (obj == null) {
				obj = _lookup(ctx, location, exactName);

				cachedObjects.put(location, obj);
			}
		} else {
			obj = _lookup(ctx, location, exactName);
		}

		return obj;
	}
	
	public static void bind (Context ctx, String location, Object object) throws NamingException {
		ctx.bind (location, object);
	}
	
	private static Object _lookup(Context ctx, String location, boolean exactName)
			throws NamingException {
		if (exactName) {
			return ctx.lookup(location);
		}
		Object obj = null;
		try {
			obj = ctx.lookup(location);
		} catch (NamingException n1) {
			// java:comp/env/ObjectName to ObjectName
			if (location.indexOf("java:comp/env/") != -1) {
				try {
					obj = ctx.lookup(StringUtils.replace(location,
							"java:comp/env/", ""));
				} catch (NamingException n2) {
					// java:comp/env/ObjectName to java:ObjectName
					obj = ctx.lookup(StringUtils.replace(location, "comp/env/",	""));
				}
			}
			// java:ObjectName to ObjectName
			else if (location.indexOf("java:") != -1) {
				try {
					obj = ctx
							.lookup(StringUtils.replace(location, "java:", ""));
				} catch (NamingException n2) {

					// java:ObjectName to java:comp/env/ObjectName

					obj = ctx.lookup(StringUtils.replace(location, "java:",
							"java:comp/env/"));
				}
			}
			// ObjectName to java:ObjectName
			else if (location.indexOf("java:") == -1) {
				try {
					obj = ctx.lookup("java:" + location);
				} catch (NamingException n2) {

					// ObjectName to java:comp/env/ObjectName

					obj = ctx.lookup("java:comp/env/" + location);
				}
			} else {
				throw new NamingException();
			}
		}

		return obj;
	}

	private static Hashtable cachedObjects = new Hashtable ();

}